//
// Created by root on 20-1-15.
//

#include <fcntl.h>
#include <sys/stat.h>
#include <cerrno>
#include "file_utils.h"
#include "log_utils.h"

#define LOG_TAG "FileUtils"

void on_read_error(const std::string &path,FILE* fp) {
    AKTagLogErr("fail to read file:%s (%s)\n", path.c_str(), strerror(errno));
    if(fp)
        fclose(fp);
}

file_size read_file(const std::string &path, char* &result) {

    const char *p_path = path.c_str();
    file_size actual_read_size=0;

    FILE* fp= fopen(p_path,"re");
    if(!fp){
        on_read_error(path,fp);
        return actual_read_size;
    }
    //获取文件大小
    struct stat so_stat;
    int fd=fileno(fp);
    if (fstat(fd, &so_stat)<0){
        on_read_error(path,fp);
        return actual_read_size;
    }
    file_size size = so_stat.st_size;
    AKLog("size:%lld\n",size);
    //读取文件
    result=(char*)malloc(size);
    actual_read_size=fread(result,1,size,fp);
    if(actual_read_size!=size){
        AKLogErr("read size mismatch(%lld/%lld)",actual_read_size,size);
    }

    return actual_read_size;
}
